package com.yshkj.payment.repository.builder;

import com.yshkj.payment.entity.medicinal.Medicinal;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 唐旭 on 2016/10/2.
 */
public class MedicinalQueryBuilder {
    //列表查询
    public Specification<Medicinal> list(Map<String, Object> query) {
        return new Specification<Medicinal>() {
            @Override
            public Predicate toPredicate(Root<Medicinal> root, CriteriaQuery<?> criteriaQuery
                    , CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                String searchKey = (String) query.get("searchKey");
                if (!StringUtils.isEmpty(searchKey)) {
                    Path<String> nameColumn = root.get("name");
                    Predicate nameLike = criteriaBuilder.like(nameColumn, "%" + searchKey + "%");
                    list.add(nameLike);

                    Join<Object, Object> specList = root.join("specList", JoinType.LEFT);
                    Path<String> codeColumn = specList.get("code");
                    Predicate codeLike = criteriaBuilder.like(codeColumn, "%" + searchKey + "%");
                    list.add(codeLike);
                    criteriaQuery.distinct(true);
                    root.join("producer", JoinType.LEFT);
                    Path<String> producerColumn = root.get("producer").get("name");
                    Predicate producerLike = criteriaBuilder.like(producerColumn, "%" + searchKey + "%");
                    list.add(producerLike);
                }

                if (list.isEmpty()) {
                    return criteriaBuilder.conjunction();
                }

                return criteriaBuilder.or(list.toArray(new Predicate[list.size()]));
            }
        };
    }
}
